<template>
  <div class="userInfo">
    <el-form class="userInfoForm" label-width="70px">
      <el-form-item label="头像">
        <image-upload
          ref="imageUpload"
          :src="userInfo.avatarUrl"
          @onUploadSuccess="onUploadSuccess"
        />
      </el-form-item>
      <el-form-item label="昵称">
        <el-input v-model="userInfo.nickName" />
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="userInfo.gender">
          <el-radio :label="0">男</el-radio>
          <el-radio :label="1">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="userInfo.phone" />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="userInfo.email" />
      </el-form-item>
      <el-form-item label="个人介绍">
        <el-input v-model="userInfo.introduction" type="textarea" :rows="5" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width: 100%;" :loading="isButtonLoading" @click="handleSave">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import imageUpload from '@/components/imageUpload'
import { getUserInfo, updateUserInfo } from '@/api/userInfo'
export default {
  name: 'UserInfo',
  components: {
    imageUpload
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      userInfo: {
        id: undefined,
        nickName: undefined,
        email: undefined,
        phone: undefined,
        gender: undefined,
        avatarUrl: undefined,
        introduction: undefined
      },
      isButtonLoading: false
    }
  },
  created() {
    this.getUserInfo()
  },
  computed: {
    ...mapGetters(['token'])
  },
  methods: {
    async getUserInfo() {
      const { data } = await getUserInfo()
      this.userInfo = data
    },
    async updateUserInfo() {
      await updateUserInfo(this.userInfo)
      this.isButtonLoading = false
      this.getUserInfo()
      this.$store.dispatch('user/getUserInfo')
    },
    handleSave() {
      this.isButtonLoading = true
      this.$refs.imageUpload.submit()
    },
    onUploadSuccess(value) {
      this.userInfo.avatarUrl = value?.data.imageUrl
      this.updateUserInfo()
    }
  }
}
</script>

<style lang="scss" scoped>
.userInfo {
    background-color: #fff;
    width: 50%;
    margin: 20px auto;
    padding: 20px 0;
    border-radius: 20px;
    box-shadow: 0 0 10px black;
    .userInfoForm {
        margin: 0 auto;
        width: 500px;
        .el-image {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            transition: all 0.1s;
            &:hover {
              box-shadow: 0 0 5px black;
            }
        }
    }
}
</style>
